package Utils.Concurrent;

import java.util.concurrent.Callable;

import org.eclipse.swt.widgets.Display;

/**
 * AsyncTask is an adapter for Callable<T> , used to add functionality to the
 * call() method (which only returns value). 
 * 
 * @author micha
 * 
 */

public abstract class AsyncTask<T> implements Callable<T> {

	protected Display display;
	protected Object[] vals;

	/**
	 * AsyncTask constructor receives a display, in which the task will be
	 * operating on. This makes sense only in case we need some widget on the
	 * display to be updated behind the scenes, in any other case, it rather be
	 * a null value or the master display of the program.
	 */
	public AsyncTask(Display display, Object... vals) {
		this.setDisplay(display);

		// handle case that no values passed
		if(vals == null)
			return;
		
		// copy all values to the inner member value array
		this.vals = new Object[vals.length];
		for (int i = 0; i < vals.length; i++) {
			this.vals[i] = vals[i];
		}
	}

	/**
	 * some long operation task, done in the background 
	 * 
	 * Essentially it is the thread 'run' method but with parameters and a
	 * generic return value
	 */
	public abstract T doInBackground();

	@Override
	public T call() {
		T result = doInBackground();
		return result;
	}

	/**
	 * executes the AsyncTask (executing the thread 'call' method) We really
	 * need only the call() function, but this for abstraction
	 * 
	 */
	public T execute() {

		return this.call();
	}

	public Display getDisplay() {
		return display;
	}

	public void setDisplay(Display display) {
		this.display = display;
	}

	public void setVals(Object... vals) {
		this.vals = vals;
	}
}
